package com.kb.erp.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kb.erp.domain.DetailSearchVO;
import com.kb.erp.domain.EmsCode;
import com.kb.erp.domain.FormField;
import com.kb.erp.domain.ProcessCenter;
import com.kb.erp.mapper.sqlServer.SynProcessCenterMapper;
import com.kb.erp.service.DYYService;
import com.kb.erp.service.SynData;
import com.kb.erp.util.MessageUtil;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@DS("slave-1")
@Slf4j
public class SynDataImpl implements SynData {

    private static List<String> emsCodeList = new ArrayList<>(Arrays.asList("fob004e6e51afe479d9a4be2bedb70b770", "fo452f2da0e76047ccb06a78ff2b6055c4"));
//    private static List<String> fileNameList7 = new ArrayList<>(Arrays.asList("fo5b3796cacc4a46428a3d204ab9fb7b75", "banana", "orange"));
//    private static List<String> conQtyList5 = new ArrayList<>(Arrays.asList("fod244bee9514e4dd8a21ed16c0dcae1d8", "banana", "orange"));
//    private static List<String> prodTypeList4 = new ArrayList<>(Arrays.asList("fo4df7ff1b1f1b40539140ec7f92c7a157", "banana", "orange"));
//    private static List<String> custCodeList3 = new ArrayList<>(Arrays.asList("fod0a259d180ae47d7b212da03ab43e239", "banana", "orange"));
//    private static List<String> conTypeList2 = new ArrayList<>(Arrays.asList("fo6140e9e90a34444cadc9c832d330911c", "banana", "orange"));
//    private static List<String> emsListList1 = new ArrayList<>(Arrays.asList("fo525e566bf0d8405293d7d54a434f7c3d", "banana", "orange"));




    @Resource
    private SynProcessCenterMapper synProcessCenterMapper;
    @Resource
    private DYYService dyyService;

    @Override
    public void synProcessCenter() {
        log.info("同步一站式编码定时任务开启");
        //获取token
        String tokenStr = HttpUtil.get("https://qwif.do1.com.cn/qwcgi/portal/api/getToken.do?" +
                "developerId=qw0d636f58fa264d15a192b3f4946dddd8&developerKey=NWQyODI3OTktOTIwMS00ODYwLWI3YWItZDk4ZDA2ZDg1YzA4");
        ObjectMapper objectMapper = new ObjectMapper();
        try {

            JsonNode jsonNode = objectMapper.readTree(tokenStr);
            JsonNode dataNode = jsonNode.get("data");
            String token = dataNode.get("token").asText();
            HashMap<String, Object> paramMap = new HashMap<>();
            DetailSearchVO detailSearchVO = new DetailSearchVO();
            detailSearchVO.setIsOver("1");
            String parse = JSONUtil.parse(detailSearchVO).toString();

            paramMap.put("detailSearchVO", parse);
            String url = "https://qwif.do1.com.cn/qwcgi/api/apiForm/getFormDetails.do?token=" + token + "&corpId=wx4f594cea21b39022&id=formc0a17264dfa342e69e68198ffd40f28e&pageSize=1";
            String post = HttpUtil.post(url, paramMap);
            JsonNode data = objectMapper.readTree(post).get("data").get("pager");
            //获取总数量
            int totalRows = objectMapper.readTree(post).get("data").get("totalRows").asInt();
            //查询行数 最大1000
            int pageSize = 1000;
            //总页数
            int totalPages = totalRows % pageSize != 0 ? totalRows / pageSize + 1 : totalRows / pageSize;
            //初始
            int page = 1;
            for (int i = 0; i < totalPages; i++) {
                long startTime = System.currentTimeMillis();

                String pageUrl = "https://qwif.do1.com.cn/qwcgi/api/apiForm/getFormDetails.do?token=" + token + "&corpId=wx4f594cea21b39022&id=formc0a17264dfa342e69e68198ffd40f28e&&page=" + page + "&pageSize=" + pageSize + "";
                System.out.println(pageUrl);
                String pagePost = HttpUtil.post(pageUrl, paramMap);
                JsonNode PageData = objectMapper.readTree(pagePost).get("data").get("pager");

                List<ProcessCenter> processCenterList = objectMapper.readValue(PageData.traverse(), new TypeReference<List<ProcessCenter>>() {
                });
                //数据转换
                for (ProcessCenter processCenter : processCenterList) {
                    //判断emscode一定要有
                    Object  emsCodeObj = null;
                    for (String s : emsCodeList) {
                        emsCodeObj = processCenter.getData().get(s);
                        if (emsCodeObj != null){
                            break;
                        }
                    }
                    if (Objects.nonNull(emsCodeObj) && emsCodeObj != "") {
                        EmsCode emsCode = new EmsCode();
                        emsCode.setEmscode(emsCodeObj.toString());
                        emsCode.setCreateTime(processCenter.getCloseTime());
                        emsCode.setCreateMan(processCenter.getClosePersonName());

                        emsCode.setCustCode(String.valueOf(processCenter.getData().get("fod0a259d180ae47d7b212da03ab43e239")));
                        Object prodTypeObj = processCenter.getData().get("fo4df7ff1b1f1b40539140ec7f92c7a157");
                        List<String> list = new ArrayList<>(Collections.singletonList(prodTypeObj.toString()));
                        emsCode.setProdType(String.join(",", list));
                        emsCode.setConType(String.valueOf(processCenter.getData().get("fo6140e9e90a34444cadc9c832d330911c")));
                        emsCode.setFileName(String.valueOf(processCenter.getData().get("fo5b3796cacc4a46428a3d204ab9fb7b75")));

                        emsCode.setEmsList(String.valueOf(processCenter.getData().get("fo525e566bf0d8405293d7d54a434f7c3d")));
                        emsCode.setConQty(Long.valueOf((String) processCenter.getData().get("fod244bee9514e4dd8a21ed16c0dcae1d8")));
                        emsCode.setDeptName(processCenter.getDepartmentName());
                        emsCode.setFlowmatch(Long.valueOf(processCenter.getIsover()));
                        List<EmsCode> processCenterDBList = synProcessCenterMapper.selectList(emsCode.getEmscode());
                        //数据不存在就插入
                        if (CollectionUtils.isEmpty(processCenterDBList)) {
                            int insertCount = synProcessCenterMapper.inserEmsCode(emsCode);
                        } else {
                            //存在就更新
                            int updateCount = synProcessCenterMapper.updateEmsCode(emsCode);
                        }
                    }
                }
                page++;
                long endTime = System.currentTimeMillis();
                long elapsedTime = endTime - startTime;
                log.info("页数为===>" + page + "，耗时====>" + elapsedTime / 1000);
            }
        } catch (Exception e) {
            log.info("流程中心全量数据更新失败-->" + e.getMessage());
        }
    }

    @Override
    public void everyDaySynProcessCenter() {
        log.info("同步一站式编码定时任务开启===" + LocalDateTime.now());
//        //获取token
//        String tokenStr = HttpUtil.get("https://qwif.do1.com.cn/qwcgi/portal/api/getToken.do?" +
//                "developerId=qw0d636f58fa264d15a192b3f4946dddd8&developerKey=NWQyODI3OTktOTIwMS00ODYwLWI3YWItZDk4ZDA2ZDg1YzA4");
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            int insertCount = 0;
            int updateCount = 0;
//            JsonNode jsonNode = objectMapper.readTree(tokenStr);
//            JsonNode dataNode = jsonNode.get("data");
//            String token = dataNode.get("token").asText();

            String token = dyyService.getDYYToken();

            //查询 -1:关闭;0:退审;1:全部审核通过;2:流转中，多个用英文竖线"|"隔开
            HashMap<String, Object> paramMap = new HashMap<>();
            DetailSearchVO detailSearchVO = new DetailSearchVO();
            detailSearchVO.setIsOver("1");
            //ormStopTime	最后处理时间	开始时间_结束时间
            // 获取当前时间
            LocalDateTime currentDateTime = LocalDateTime.now();
            // 获取两天前的日期
            LocalDateTime twoDaysAgo = currentDateTime.minusDays(2);
            // 将日期格式化为字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedTwoDaysAgo = twoDaysAgo.format(formatter);
            String formattedNow = currentDateTime.format(formatter);
            String time = formattedTwoDaysAgo+"_"+formattedNow;
            detailSearchVO.setFormStopTime(time);

            String parse = JSONUtil.parse(detailSearchVO).toString();
            paramMap.put("detailSearchVO", parse);

            int pageSize = 1000;
            String pageUrl = "https://qwif.do1.com.cn/qwcgi/api/apiForm/getFormDetails.do?token=" + token + "&corpId=wx4f594cea21b39022&id=formc0a17264dfa342e69e68198ffd40f28e&pageSize=" + pageSize ;
            log.info(pageUrl);
            XxlJobHelper.log(pageUrl );
            String pagePost = HttpUtil.post(pageUrl, paramMap);
            JsonNode PageData = objectMapper.readTree(pagePost).get("data").get("pager");
            XxlJobHelper.log(LocalDateTime.now() + "--->没有新数据");
            if (Objects.isNull(PageData)){
                return;
            }
            List<Map<String, Object>> processCenterMap = objectMapper.readValue(PageData.traverse(), new TypeReference<List<Map<String, Object>>>() {
            });
            if (CollectionUtil.isEmpty(processCenterMap)){
                log.info(LocalDateTime.now() + "--->没有新数据");
                XxlJobHelper.log(LocalDateTime.now() + "--->没有新数据");
               return;
            }

            //获取最新版本的key
            String keyUrl = "https://qwif.do1.com.cn/qwcgi/api/apiForm/ajaxGetFormFieldInfoSimple.do?token=" + token + "&corpId=wx4f594cea21b39022&id=formc0a17264dfa342e69e68198ffd40f28e";
            log.info(keyUrl);
            XxlJobHelper.log(keyUrl);
            HashMap<String, Object> keyMap = new HashMap<>();
            String keyMapStr = HttpUtil.post(keyUrl, keyMap);
            JsonNode keyData = objectMapper.readTree(keyMapStr).get("data").get("formField");
            List<FormField> formFieldList = objectMapper.readValue(keyData.traverse(), new TypeReference<List<FormField>>() {
            });
            String custCode =  "fod0a259d180ae47d7b212da03ab43e239";
            String prodType =  "fo4df7ff1b1f1b40539140ec7f92c7a157";
            String conType =  "fo6140e9e90a34444cadc9c832d330911c";
            String fileName =  "fo5b3796cacc4a46428a3d204ab9fb7b75";
            String emsList =  "fo525e566bf0d8405293d7d54a434f7c3d";
            String conQty =  "fod244bee9514e4dd8a21ed16c0dcae1d8";
            String emsCodeStr =  "fob004e6e51afe479d9a4be2bedb70b770";

            //查询客户代码
            List<String> oldCustCodeList = synProcessCenterMapper.selectCustCode();
            //去除空格
            List<String> custCodeList = new ArrayList<>();
            for (String s : oldCustCodeList) {
                custCodeList.add(s.trim());
            }
            for (FormField formField : formFieldList) {
                if (Objects.equals("客户代码",formField.getLabel())){
                    custCode = formField.get_id();
                }
                if (Objects.equals("业务类型",formField.getLabel())){
                    prodType = formField.get_id();
                }
                if (Objects.equals("合同类型",formField.getLabel())){
                    conType = formField.get_id();
                }
                if (Objects.equals("文件名",formField.getLabel())){
                    fileName = formField.get_id();
                }
                if (Objects.equals("编码类型(自动生成)",formField.getLabel())){
                    emsList = formField.get_id();
                }
                if (Objects.equals("数量",formField.getLabel())){
                    conQty = formField.get_id();
                }
                if (Objects.equals("一站式编码",formField.getLabel())){
                    emsCodeStr = formField.get_id();
                }
            }
            //数据转换
            for (Map<String, Object> objectMap : processCenterMap) {
                Map data = (Map) objectMap.get("data");

                String value =String.valueOf(data.get(custCode));
                //判断emscode一定要有
                Object emsCodeObj = data.get(emsCodeStr);
                if (Objects.nonNull(emsCodeObj) && emsCodeObj != "" && (custCodeList.contains(value) || value.startsWith("EC"))) {
                    EmsCode emsCode = new EmsCode();
                    emsCode.setEmscode(emsCodeObj.toString());
                    emsCode.setCreateTime((String) objectMap.get("closeTime"));
                    emsCode.setCreateMan((String) objectMap.get("closePersonName"));
                    emsCode.setCustCode(value);
                    Object prodTypeObj = data.get(prodType);
                    List<String> list = new ArrayList<>(Collections.singletonList(prodTypeObj.toString()));
                    emsCode.setProdType(String.join(",", list));
                    emsCode.setConType(String.valueOf(data.get(conType)));
                    emsCode.setFileName(String.valueOf(data.get(fileName)));
                    emsCode.setEmsList(String.valueOf(data.get(emsList)));

                    //处理小数
                    String str = (String) data.get(conQty);
                    String integerPart = str.split("\\.")[0]; // 取小数点前的部分
                    emsCode.setConQty( Long.parseLong(integerPart));

                    emsCode.setDeptName((String) objectMap.get("departmentName"));
                    emsCode.setFlowmatch(Long.valueOf((String) objectMap.get("isover")));
                    List<EmsCode> processCenterDBList = synProcessCenterMapper.selectList(emsCode.getEmscode());
                    //数据不存在就插入
                    if (CollectionUtils.isEmpty(processCenterDBList)) {
                        synProcessCenterMapper.inserEmsCode(emsCode);
                        insertCount++;
                    } else {
                        //存在就更新
                        synProcessCenterMapper.updateEmsCode(emsCode);
                        updateCount++;
                    }
                }
            }
            log.info(LocalDateTime.now() + "--->插入条数: " + insertCount + "-->更新条数: " + updateCount);
            XxlJobHelper.log(LocalDateTime.now() + "--->插入条数: " + insertCount + "-->更新条数: " + updateCount);
        } catch (Exception e) {
            MessageUtil.sentMessageToAssistant("23988", e.getMessage());
            log.info(LocalDateTime.now()+"-->流程中心每日数据更新失败-->" + e.getMessage());
            XxlJobHelper.log(LocalDateTime.now()+"-->流程中心每日数据更新失败-->" + e.getMessage());
            throw new RuntimeException("流程中心每日数据更新失败-->" + e.getMessage());
        }

    }

    public static void main(String[] args) {
        // 获取当前时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 获取两天前的日期
        LocalDateTime twoDaysAgo = currentDateTime.minusDays(2);

        // 将日期格式化为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTwoDaysAgo = twoDaysAgo.format(formatter);
        String formattedTwoDaysAgo1 = currentDateTime.format(formatter);


        System.out.println("两天前的日期和时间是：" + formattedTwoDaysAgo);
        System.out.println("两天前的日期和时间是：" + formattedTwoDaysAgo1);
    }

}
